/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    ListNode* reverseList(ListNode* head) {
    ListNode* prev = nullptr;
    while (head) {
        ListNode* next = head->next;
        head->next = prev;
        prev = head;
        head = next;
    }
    return prev;
}

ListNode* addInList(ListNode* head1, ListNode* head2) {
    head1 = reverseList(head1);
    head2 = reverseList(head2);
    
    ListNode dummy(0);
    ListNode* curr = &dummy;
    int carry = 0;
    
    while (head1 || head2 || carry) {
        int sum = carry;
        if (head1) {
            sum += head1->val;
            head1 = head1->next;
        }
        if (head2) {
            sum += head2->val;
            head2 = head2->next;
        }
        
        carry = sum / 10;
        curr->next = new ListNode(sum % 10);
        curr = curr->next;
    }
    
    return reverseList(dummy.next);
}
};